package com.example.springboot.utils;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisUtil {
    @Autowired
    static RedisTemplate redisTemplate;


    public static void saveString(String key,String value) {
        redisTemplate.opsForValue().set(key,value);

    }

    public static void deleteKey(String key){
        redisTemplate.delete(key);
    }


    public static String getString(String key) {
        if (redisTemplate.hasKey(key)) return redisTemplate.opsForValue().get(key).toString();
        return null;
    }


    public static void saveObject(String key,Object value) throws JsonProcessingException {

        //将对象转为Json
        String json = JSONUtil.toJsonStr(value);

        //将对象的Json存到redis
        redisTemplate.opsForValue().set(key,json);


    }

    public static Object getObject(String key) {
        //从Redis中得到对象强制转为对象
        String json = (String) redisTemplate.opsForValue().get(key);
        //Json转化为对象实例
        return   JSONUtil.toBean(json, Object.class);

    }


}
